<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/2/5
 * Time: 16:48
 */
namespace app\admin\service;

use app\common\Model\BannerType;

use think\Db;

class BannerTypeService
{
    //移动排序
    public static function alterBannerSort($ids, $sort)
    {
        if ($sort == 1) {
            $order = 'sort asc';
            $compare = '<=';
            $orders = 'sort desc';
        }else{
            $order = 'sort desc';
            $compare = '>=';
            $orders = 'sort asc';
        }
        $ids = BannerType::where('id', 'in', $ids)->where('is_del', 0)->order($order)->select()->toArray();
        // 启动事务
        Db::startTrans();
        try {
            foreach ($ids as $v) {
                $twoFC = BannerType::where('is_del', 0)->where('sort', $compare, $v['sort'])->order($orders)->limit(2)->select()->toArray();
                if(count($twoFC)==1){
                    Db::rollback();
                    return 2;
                }
                $updata = [
                    [
                        'id' => $twoFC[0]['id'],
                        'sort' => $twoFC[1]['sort'],
                    ],
                    [
                        'id' => $twoFC[1]['id'],
                        'sort' => $twoFC[0]['sort'],
                    ],
                ];
                $BannerType = new BannerType();
                $BannerType->saveAll($updata);
            }
            // 提交事务
            Db::commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 0;
        }
    }
}